# coding=utf-8
# author=haishan09@gmail.com
from collections import OrderedDict 
from chart.adapters.base import BaseAdapter
from utils.types import OrderedDefaultDict
from common.provider import provider_register


@provider_register('chartadapter', 'scatter')
class scatterAdapter(BaseAdapter):

    def transform(self, config, source):
        xaxis = OrderedDict()
        legend = []
        cells = OrderedDefaultDict(lambda: [])
        dimensions = map(lambda d: d['drilldown'], config['drilldowns'])
        aggregates = map(lambda d: d['aggregate'], config['aggregates'])
        legend_max_len = int(config['chart']['legend.max.length'])
        for cell in source['cells']:
            legend_item = '_'.join(map(lambda dim_name:cell.get(dim_name), dimensions))
            values = []
            if not legend_item in legend:
                legend.append(legend_item)
            for agg_name in aggregates:
                value = cell.get(agg_name, 0)
                values.append(value)
            cells[legend_item].append(values)
        retdict = {}
        retdict['xaxis'] = xaxis.keys()
        cells_items = cells.items()
        retdict['legend'] = legend[:legend_max_len]
        retdict['cells'] = OrderedDict(cells_items[:legend_max_len])
        if len(legend) > legend_max_len:
            retdict['legend'] += [u'其他']
            retdict['cells'][u'其他'] = reduce(
                lambda x, y: x + y, 
                map(lambda (k, v): v, cells_items[legend_max_len:])
                )
        return retdict

